package cn.doitedu.server;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServerDemo {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line = br.readLine();

            // GET /index.html HTTP/1.1
            String url = line.split(" ")[1];
            /*String[] arr = url.split("\\?");
            String path = arr[0];
            String paramRaw = arr[1];
            System.out.println(path);
            System.out.println(paramRaw);*/

            File htmlFile;
            switch (url) {
                case "/index.html":
                    htmlFile = new File("htmls/index.html");
                    sendResponse(htmlFile, outputStream);
                    break;
                case "/a.html":
                    htmlFile = new File("htmls/a.html");
                    sendResponse(htmlFile, outputStream);
                    break;
                default:
                    htmlFile = new File("htmls/404.html");
                    sendResponse(htmlFile, outputStream);
            }

            outputStream.close();
            socket.close();

        }

    }

    private static void sendResponse(File htmlFile, OutputStream outputStream) throws IOException {
        // 准备响应头
        String statusLine = "HTTP/1.1 200 OK\r\n";   // 响应行
        String contentType = "Content-Type: text/html; charset=utf-8\r\n";  // 响应头
        String contentLength = "Content-Length: "+ htmlFile.length()+"\r\n\r\n";

        // 发送响应头
        outputStream.write(statusLine.getBytes());
        outputStream.write(contentType.getBytes());
        outputStream.write(contentLength.getBytes());
        // 发送响应体
        FileInputStream fileInputStream = new FileInputStream(htmlFile);
        IOUtils.copy(fileInputStream, outputStream);

        outputStream.flush();
        fileInputStream.close();
    }
}
